package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MybatisSqlSession {
    private static SqlSessionFactory factory;
    private static SqlSession sqlSession;

    private MybatisSqlSession() {
    }

    static {
        try {
            factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
        sqlSession = factory.openSession();
        return sqlSession;

    }

    public static Object getMapper(Class mapperClass){
        SqlSession sqlSession = getSqlSession();
        Object mapper = sqlSession.getMapper(mapperClass);
        Object mapperProxy = Proxy.newProxyInstance(mapper.getClass().getClassLoader(), mapper.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object invoke = null;
                try {
                    invoke = method.invoke(mapper, args);
                    sqlSession.commit();
                } catch (Exception e) {
                    sqlSession.rollback();
                    e.printStackTrace();
                } finally {
                    sqlSession.close();
                }
                return invoke;
            }
        });
        return mapperProxy;
    }



    public static void close() {
        if (sqlSession != null) {
            sqlSession.commit();
            sqlSession.close();
        }
    }

}
